#include "LinkGrabber.h"




#ifndef BUFFER_MAXLENGTH
#define BUFFER_MAXLENGTH 4096
#endif

#ifndef FBUFFER_MAXLENGTH
#define FBUFFER_MAXLENGTH 10000
#endif


//enable me to easily write to a file
void writefile(wxString filename, wxInputStream& stream)
	{
	wxFile file(filename, wxFile::write);
	unsigned char buffer[BUFFER_MAXLENGTH];

	do{
		stream.Read(buffer,BUFFER_MAXLENGTH);
		size_t bytesread = stream.LastRead();

		if(bytesread > 0) file.Write(buffer,bytesread);
		}while(!stream.Eof());

	file.Close();
	}




LinkGrabber::LinkGrabber()
	{
	}

LinkGrabber::LinkGrabber(wxString url)
	{
	PageUrl = url;
	this->SetPage(url);
	}



bool LinkGrabber::SetPage(wxString url)
	{
	PageReqUrl = url;

	if(PageReqUrl.GetError() == wxURL_NOERR){

		wxInputStream* InStream = PageReqUrl.GetInputStream();
		if(!InStream) wxMessageBox( wxT("Error creating input stream") );
		
		wxString filename(wxT("VideoPage.html"));
	
		wxFile TempResults(filename,wxFile::write);


		unsigned char buffer[BUFFER_MAXLENGTH];

		do{
			InStream->Read(buffer,BUFFER_MAXLENGTH);
			size_t bytesread = InStream->LastRead();

			if(bytesread > 0) {
				TempResults.Write(buffer,bytesread);
				}
			}while(!InStream->Eof());

		delete InStream;
		TempResults.Close();
		
		
		Filename = filename;	

		return true;
		}
	else{
		return false;
		}
	}



wxString LinkGrabber::GetDirectLink()  //search for first "swfArgs and get it until the first ";"
	{
	
	std::string page;
	//wxString str;
	//wxTextFile tfile;

	//tfile.Open(Filename);
	//str = tfile.GetFirstLine();


	std::ifstream in(Filename.c_str());
	char buf[FBUFFER_MAXLENGTH];

	while(!in.eof())
		{
		in.getline(buf,FBUFFER_MAXLENGTH);
		page += buf;
		}
	
	

	/*
	while(!tfile.Eof()){
		str.Append(tfile.GetNextLine());
		};*/
	
	//RawPageData = str;

	//this assumes that we want to download the low quality video
	//to go higher quality, increase "t" to 46 chars and don't add an "=" at the end
	Narrowing_Expression = "(video_id=\\S{1,}&.{1,}&t=\\S{1,42})+[^&]";//+[^;]{1,}";
	Pre_Expression = "(video_id=\\S{1,11})&.{1,}(&t=\\S{1,42})";//&hl=.{1,}";
	//Note: by including fmt=18 into this link, we force youtube to give us the .mp4
	//version of the file.  Unfortunately, this mp4 version can be differently sized than
	//all of the .flv files, which are all QVGA format (320x240).
	Pre_Format = "http://www.youtube.com/get_video?fmt=18&$1$2";
	Pre_Format_ID = "$1";
	

	//this narrows it down to just the video_id part***********************************
	SearchRegEx.assign(Narrowing_Expression);
	UrlRegEx.assign(Pre_Expression);

	
	//std::string page = "video_id=qS1f9Fby3bA&l=230&sk=OusfSa3hwWJHEf71sMYnl79vGokJm-XwC&fmt_map=&t=OEgsToPDskJCyVf2wauPxZycnNAL51I-&hl=en&plid=AARUNme0dQVA1NADAAAAoAB8AQA&iv_module=http%3A%2F%2Fs.ytimg.com%2Fyt%2Fswf%2Fiv_module-vfl49883.swf&tk";
	boost::match_results<std::string::const_iterator> what;
	std::string::const_iterator start,end;

	start = page.begin();
	end = page.end();

	std::ofstream os2("DebugStrings.txt");
	
	std::string result,res2;
	if(boost::regex_search(start,end,what,SearchRegEx,boost::match_default))
		{
		//ugly way of getting the smallscreen version.  We omit the "%3D" when
		//grabbing the link and replace it with a "="
		
		result = what[0].str()+"="; //entire link, including title
		res2 = what[1].str();  //link until the first space in the title
		
		}
	
	
	os2<<"FIRST: "<<result<<"\n\n\n "<<"SECOND: "<<res2<<"\n\n\n";
	os2.close();
	//now we have the video_id part of the html file***********************

	


	std::ofstream os("DirectLink.txt");
	
	std::string args = boost::regex_replace(result,
		UrlRegEx,Pre_Format,boost::match_default | boost::format_all);
	
	os << args;

	os.close();

	//Gets the Video_Id for later filenaming purposes
	std::string fname = boost::regex_replace(result,
		UrlRegEx,Pre_Format_ID, boost::match_default | boost::format_no_copy);
	
	fname_Id = fname; //so we can access the video_id with GetFnameId()


	//get the return value into a wxString
	const char* temp;
	temp = args.c_str();

	wxString ret_DirLink(temp,wxConvUTF8);
	

	
	return ret_DirLink;
	
	}

wxString LinkGrabber::GetFnameId()
	{
	const char* temp;
	temp = fname_Id.c_str();
	wxString ret_Id(temp,wxConvUTF8);

	return ret_Id;
	}



